"""
cron: 0 */4 * * *
new Env('音乐排行榜采集');
"""
import requests
import os
import mysql.connector
from datetime import datetime

# 获取环境变量
host = os.environ.get('HOST')
user = os.environ.get('USER')
password = os.environ.get('PASSWORD')
database = os.environ.get('DATABASE')

print("正在获取环境变量...")
print(f"数据库地址：{host}")
print(f"数据库用户名：{user}")
print(f"数据库密码：{password}")
print(f"数据库名称：{database}")

# 发送HTTP请求获取网易云音乐排行榜
print("发送HTTP请求获取音乐排行榜数据...")
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}

# 网易云音乐飙升榜API
url = 'https://music.163.com/api/v3/playlist/detail'
params = {
    'id': '19723756',  # 飙升榜ID
    'limit': 20
}

response = requests.get(url, headers=headers, params=params)

# 连接数据库
connection = mysql.connector.connect(
    host=host,
    user=user,
    password=password,
    database=database
)

cursor = connection.cursor()

# 创建表（如果不存在）
create_table_query = """
CREATE TABLE IF NOT EXISTS ningm_music_rank (
    id INT AUTO_INCREMENT PRIMARY KEY,
    song_name VARCHAR(200) NOT NULL,
    artist VARCHAR(200),
    album VARCHAR(200),
    play_count INT,
    platform VARCHAR(50),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_platform (platform),
    INDEX idx_create_time (create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
"""
cursor.execute(create_table_query)

# 删除旧数据（保留1天内的数据）
print("删除旧数据...")
delete_query = "DELETE FROM ningm_music_rank WHERE create_time < DATE_SUB(NOW(), INTERVAL 1 DAY)"
cursor.execute(delete_query)

# 解析并保存数据
print("解析并保存音乐排行榜数据...")
if response.status_code == 200:
    data = response.json()
    songs = data.get('playlist', {}).get('tracks', [])
    
    for song in songs[:20]:  # 只取前20首
        song_name = song.get('name', '')
        artist = song.get('ar', [{}])[0].get('name', '')
        album = song.get('al', {}).get('name', '')
        
        print(f"正在保存歌曲数据: {song_name} - {artist}")
        insert_query = """
            INSERT INTO ningm_music_rank 
            (song_name, artist, album, platform) 
            VALUES (%s, %s, %s, %s)
        """
        insert_values = (
            song_name,
            artist,
            album,
            'netease'
        )
        cursor.execute(insert_query, insert_values)

connection.commit()
cursor.close()
connection.close()

print("数据保存完成！") 